package com.osmino.core;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;

public final class TextPickerDialog extends AlertDialog {

	private EditText mEditText;
	
	public TextPickerDialog(Context context) {
		super(context);
		mEditText = new EditText(context);
		mEditText.setInputType(EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
		mEditText.setLayoutParams(new ViewGroup.MarginLayoutParams(4, 0));
		mEditText.setSingleLine(true);
		setView(mEditText);
	}
	
	public EditText getEditText() {
		return mEditText;
	}
	
	@Override
	public void setButton(CharSequence text, Message msg) {
		super.setButton(text, msg);
		setPositiveButtonEnabler();
	}
	
	@Override
	public void setButton(CharSequence text, OnClickListener listener) {
		super.setButton(text, listener);
		setPositiveButtonEnabler();
	}
	
	@Override
	public void setButton(int whichButton, CharSequence text, Message msg) {
		super.setButton(whichButton, text, msg);
		if (whichButton == BUTTON_POSITIVE) {
			setPositiveButtonEnabler();
		}
	}
	
	@Override
	public void setButton(int whichButton, CharSequence text, OnClickListener listener) {
		super.setButton(whichButton, text, listener);
		if (whichButton == BUTTON_POSITIVE) {
			setPositiveButtonEnabler();
		}
	}
	
	private void setPositiveButtonEnabler() {
		Button positiveButton = getButton(BUTTON_POSITIVE);
		mEditText.addTextChangedListener(new EnterTextDialogCallback(positiveButton));
		positiveButton.setEnabled(mEditText.getText().toString().trim().length() != 0);
	}
	
	public void prepare() {
		Button positiveButton = getButton(BUTTON_POSITIVE);
		mEditText.setText("");
		if (positiveButton != null) {
			positiveButton.setEnabled(false);			
		}
	}
	
	private static final class EnterTextDialogCallback implements TextWatcher {

		private Button positiveButton;

		public EnterTextDialogCallback(Button positiveButton) {
			this.positiveButton = positiveButton;
		}

		@Override
		public void afterTextChanged(Editable s) {
			//
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			//
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			positiveButton.setEnabled(s.toString().trim().length() != 0);
		}

	}

}
